package com.centling.task;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.centling.business.CustomerBean;
import com.centling.controller.CustomerController;
import com.centling.controller.model.CustomerVO;
import com.centling.service.ICustomerService;
import com.centling.service.IUtilsService;
import com.centling.util.DateUtils;
import com.centling.util.Encryption;
import com.centling.util.LocalUtils;

@Component
@Transactional
public class CustomerInfoImportTasks {

	private static Logger log = Logger.getLogger(CustomerInfoImportTasks.class);

	@Resource
	private ICustomerService customerService;
	
	@Resource
	private IUtilsService utilsService;

	@Value("${task.customer.import.post_url}")
	private String post_url;
	
	@Value("${task.customer.import.num}")
	private Integer num;
	
	@Value("${task.customer.import.daynum}")
	private Integer daynum;
	
	/**
	 * This task will be performed every 。。。 minutes
	 * @throws Exception 
	 */
	@Scheduled(cron = "0 0/${task.customer.import.mintus} * * * *")
	@Transactional
	private void CustomerInfoImportCRM() throws Exception {
		/*log.info("Performing Scheduled task: customers Import CRM");
		String beginTime	= DateUtils.addDay(DateUtils.getCurrDate(), daynum)+" 00:00:00";
		String endTime		= DateUtils.getCurrDate()+" 23:59:59";
		log.info("offlinemeasure info request BeginTime:	"+beginTime);
		log.info("offlinemeasure info request endTime  :	"+endTime);
		log.info("offlinemeasure info request num      :	"+num);
		
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("beginTime", beginTime);
		paramMap.put("endTime", endTime);
		paramMap.put("num", num);
		
		// Post请求的url，与get不同的是不需要带参数
        URL postUrl = new URL(post_url);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection
                .getOutputStream());
    	
    	String str = JSON.toJSONString(paramMap);
    	
    	String mi = Encryption.encrypt(str, "RCCRMKEY");
        String content = "encryptionJsonStr=" + URLEncoder.encode(mi, "utf-8");
        out.writeBytes(content); 

        out.flush();
        out.close(); // flush and close
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        StringBuffer sb = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        connection.disconnect();
        
        String jsonStr=Encryption.decrypt(sb.toString(), CustomerController.RC_CRM_KEY); 
		log.info("param after: " + jsonStr);
		JSONArray jsonArr = JSON.parseArray(jsonStr);
		List<CustomerBean> list = new ArrayList<CustomerBean>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for (int i=0; i<jsonArr.size(); i++){
			CustomerVO vo = JSON.toJavaObject(jsonArr.getJSONObject(i), CustomerVO.class);
			CustomerBean cb = new CustomerBean();
			cb.setF_system_source(vo.getF_system_source());
			cb.setF_other_customer_code(vo.getF_other_customer_code());
			cb.setfName(vo.getfName());
			cb.setF_customer_source(vo.getF_customer_source());
			cb.setF_customer_type((vo.getF_customer_type()!=null&&vo.getF_customer_type()==1)?"是":"否");
			if(LocalUtils.isNotNull(vo.getFsex()))cb.setFsex(vo.getFsex().toString());
			if(LocalUtils.isNotBlank(vo.getfBirthday())){
				Date date = (Date)sdf.parse(vo.getfBirthday());
				cb.setfBirthday(date);
				cb.setfAge(LocalUtils.calTwoTimeSpace(date, new Date(), Calendar.YEAR));
			}
			if(LocalUtils.isNotBlank(vo.getFnation()))cb.setFnation(vo.getFnation());
			if(LocalUtils.isNotBlank(vo.getF_persional_faith()))cb.setF_persional_faith(vo.getF_persional_faith());
			if(LocalUtils.isNotBlank(vo.getF_personal_taboo()))cb.setF_personal_taboo(vo.getF_personal_taboo());
			if(LocalUtils.isNotBlank(vo.getF_education()))cb.setF_education(vo.getF_education());
			if(LocalUtils.isNotBlank(vo.getF_marital_status()))cb.setF_marital_status(vo.getF_marital_status());
			if(LocalUtils.isNotNull(vo.getF_marital_date()))cb.setF_marital_date((Date)sdf.parse(vo.getF_marital_date()));
			if(LocalUtils.isNotBlank(vo.getF_memorial_name()))cb.setF_memorial_name(vo.getF_memorial_name());
			if(LocalUtils.isNotBlank(vo.getF_memorial_date()))cb.setF_memorial_date((Date)sdf.parse(vo.getF_memorial_date()));
			if(LocalUtils.isNotBlank(vo.getfComboBox8()))cb.setfComboBox8(vo.getfComboBox8());
			if(LocalUtils.isNotBlank(vo.getfComboBox9()))cb.setfComboBox9(vo.getfComboBox9());
			if(LocalUtils.isNotBlank(vo.getfCountry()))cb.setfCountry(vo.getfCountry());
			if(LocalUtils.isNotBlank(vo.getF_province()))cb.setF_province(vo.getF_province());
			if(LocalUtils.isNotBlank(vo.getF_city()))cb.setF_city(vo.getF_city());
			if(LocalUtils.isNotBlank(vo.getfRegionName()))cb.setfRegionID(LocalUtils.getRegionIDByRegionName(vo.getfRegionName()));
			String faddress = "";
			if(LocalUtils.isNotBlank(vo.getfProvinceName())){
				Integer provinceid = LocalUtils.getProvinceIDByProvinceName(vo.getfProvinceName());
				cb.setfProvinceID(provinceid);
				faddress += provinceid==null?"":vo.getfProvinceName();
			}
			
			if(LocalUtils.isNotBlank(vo.getfCityName())){
				Integer cityid = utilsService.getCityIDByCityName(vo.getfCityName());
				cb.setfCityID(cityid);
				faddress += cityid==null?"":vo.getfCityName();
			}
			if(LocalUtils.isNotBlank(vo.getfAddress()))faddress += vo.getfAddress();
			if(LocalUtils.isNotBlank(faddress))cb.setfAddress(faddress);
			if(LocalUtils.isNotBlank(vo.getfPhone()))cb.setfPhone(vo.getfPhone());
			if(LocalUtils.isNotBlank(vo.getfMobile()))cb.setfMobile(vo.getfMobile());
			if(LocalUtils.isNotBlank(vo.getfEmail()))cb.setfEmail(vo.getfEmail());
			if(LocalUtils.isNotBlank(vo.getF_QQ()))cb.setF_QQ(vo.getF_QQ());
			if(LocalUtils.isNotBlank(vo.getF_skype()))cb.setF_skype(vo.getF_skype());
			if(LocalUtils.isNotBlank(vo.getF_micro_message()))cb.setF_micro_message(vo.getF_micro_message());
			if(LocalUtils.isNotBlank(vo.getF_micro_blog()))cb.setF_micro_blog(vo.getF_micro_blog());
			if(LocalUtils.isNotBlank(vo.getfWorkUnit()))cb.setfWorkUnit(vo.getfWorkUnit());
			if(LocalUtils.isNotBlank(vo.getfTradeName()))cb.setfTrade(LocalUtils.getTradeIDByTradeName(vo.getfTradeName()));
			if(LocalUtils.isNotBlank(vo.getF_work()))cb.setF_work(vo.getF_work());
			if(LocalUtils.isNotBlank(vo.getfDuty()))cb.setfDuty(vo.getfDuty());
			if(LocalUtils.isNotBlank(vo.getfWorkSite()))cb.setfWorkSite(vo.getfWorkSite());
			if(LocalUtils.isNotBlank(vo.getfBizPhone()))cb.setfBizPhone(vo.getfBizPhone());
			if(LocalUtils.isNotBlank(vo.getfFax()))cb.setfFax(vo.getfFax());
			if(LocalUtils.isNotBlank(vo.getF_company_size()))cb.setF_company_size(vo.getF_company_size());
			if(LocalUtils.isNotBlank(vo.getfHomePage()))cb.setfHomePage(vo.getfHomePage());
			if(LocalUtils.isNotBlank(vo.getF_dressing_specification()))cb.setF_dressing_specification(vo.getF_dressing_specification());
			if(LocalUtils.isNotBlank(vo.getF_remarks()))cb.setF_remarks(vo.getF_remarks());
			list.add(cb);
		}
		Boolean returnVal = customerService.save(list);
		log.info("function ecCustomerImport end..., with return " + returnVal);*/
	}
}
